import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:redbook_app/api.dart';
import 'package:saver_gallery/saver_gallery.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:dynamic_height_grid_view/dynamic_height_grid_view.dart';

import 'VideoDownloader.dart';

class Tabcontent extends StatefulWidget {
  final int status;
  const Tabcontent({super.key, required this.status});

  @override
  State<Tabcontent> createState() => _TabcontentState();
}

class _TabcontentState extends State<Tabcontent> {
  var serverUrl = "";
  List<dynamic> list = [];

  Future<void> _loadConfig() async {
    final prefs = await SharedPreferences.getInstance();
    serverUrl = prefs.getString("server_url") ?? "http://127.0.0.1:8099";
  }

  Future<void> _loadData() async {
    print(widget.status);
    var statusStr = widget.status.toString();
    var url = Uri.parse(serverUrl + (API["GET_JOBS"] ?? "")).replace(queryParameters: {"status": statusStr});
    var resp = await http.get(url);
    var result = jsonDecode(resp.body);
    print(result["data"]);
    setState(() {
      list = result["data"];
    });
  }

  Future<void> _init() async {
    await _loadConfig();
    await _loadData();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _init();
  }

  // 请求权限

  Future<void> _downloadVideo(info) async {
    final videoUrl = "$serverUrl/video/${info["name"]}.mp4";
    final downloader = VideoDownloader();
    await downloader.requestPermission();
    String fileName = 'video_${DateTime.now().millisecondsSinceEpoch}.mp4';
    bool success = await downloader.downloadAndSaveVideo(videoUrl, fileName);
    if (success) {
      print('视频已成功下载并保存到相册');
      Fluttertoast.showToast(
          msg: "视频已成功下载并保存到相册",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.TOP,
          timeInSecForIosWeb: 2,
          backgroundColor: Colors.green[300],
          textColor: Colors.white,
          fontSize: 14.0);
    } else {
      print('视频保存失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 10, right: 10),
      child: DynamicHeightGridView(
        itemCount: list.length,
        crossAxisCount: 2,
        builder: (ctx, index) {
          var info = list[index];
          return Container(
            // height: 500,

            child: Column(
              children: [
                Image.network(
                  '$serverUrl/poster/${info['name']}.jpg',
                  fit: BoxFit.cover,
                ),
                Text(info['name']),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    TextButton(
                        onPressed: () {
                          Navigator.pushNamed(context, "/video_play",
                              arguments: {"url": "$serverUrl/video/${info["name"]}.mp4"});
                        },
                        child: Text("播放")),
                    TextButton(
                        onPressed: () {
                          _downloadVideo(info);
                        },
                        child: Text("下载")),
                  ],
                )
              ],
            ),
          );
        },
      ),
    );
  }
}
